package com.hfjyz.expert.expert.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.hfjyz.base.action.GridBaseAction;
import com.hfjyz.base.exception.BaseException;
import com.hfjyz.base.util.BaseUtil;
import com.hfjyz.expert.expert.bean.ExpertBean;
import com.hfjyz.expert.expert.bean.ExpertExcelBean;
import com.hfjyz.expert.expert.bean.ExpertSearchBean;
import com.hfjyz.expert.expert.service.ExpertService;
import com.hfjyz.expert.expertcall.bean.ExpertCallBean;
import com.hfjyz.expert.expertcall.service.ExpertCallService;

public class ExpertAutoSelectAction extends GridBaseAction {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 2363637918721745365L;

    private ExpertSearchBean expertSearch = null;
    private Integer autoSelectCount = null;
    private ExpertCallBean expertCall = null;
    private String expertIds = null;

    private InputStream excelStream = null;
    private String downloadFileName = null;

    private ExpertService service = null;

    private ExpertCallService callService = null;

    public InputStream getExcelStream() {
        return excelStream;
    }

    public void setExcelStream(InputStream excelStream) {
        this.excelStream = excelStream;
    }

    public String getDownloadFileName() {
        return downloadFileName;
    }

    public void setDownloadFileName(String downloadFileName) {
        this.downloadFileName = downloadFileName;
    }

    public ExpertSearchBean getExpertSearch() {
        return expertSearch;
    }

    public void setExpertSearch(ExpertSearchBean expertSearch) {
        this.expertSearch = expertSearch;
    }

    public Integer getAutoSelectCount() {
        return autoSelectCount;
    }

    public void setAutoSelectCount(Integer autoSelectCount) {
        this.autoSelectCount = autoSelectCount;
    }

    public ExpertCallBean getExpertCall() {
        return expertCall;
    }

    public void setExpertCall(ExpertCallBean expertCall) {
        this.expertCall = expertCall;
    }

    public ExpertService getService() {
        return service;
    }

    public void setService(ExpertService service) {
        this.service = service;
    }

    public ExpertCallService getCallService() {
        return callService;
    }

    public void setCallService(ExpertCallService callService) {
        this.callService = callService;
    }

    public String getExpertIds() {
        return expertIds;
    }

    public void setExpertIds(String expertIds) {
        this.expertIds = expertIds;
    }

    @Override
    protected List<ExpertBean> getBeanList() throws BaseException {
        List<ExpertBean> expertList = service.findExpertWithoutPage(getSearchCondition(), expertSearch);
        if (autoSelectCount == null) {
            return expertList;
        }
        Set<Integer> indexSet = BaseUtil.getRandomIndex(expertList.size(), autoSelectCount);
        List<ExpertBean> retList = new ArrayList<ExpertBean>();
        Iterator<Integer> it = indexSet.iterator();
        while (it.hasNext()) {
            retList.add(expertList.get(it.next()));
        }
        return retList;
    }

    @Override
    protected long getTotalCount() throws BaseException {
        long count = service.getExpertCount(expertSearch);
        if (autoSelectCount == null) {
            return count;
        }
        if (count < autoSelectCount) {
            return count;
        } else {
            return autoSelectCount;
        }
    }

    public String export() throws BaseException {
        ByteArrayOutputStream baos = null;
        try {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/");
            String templatePathSingle = rootPath + "WEB-INF\\conf\\expert\\"
                    + ExpertExcelAction.XLS_EXPERT_TEMPLATE;
            String templatePathMulti = rootPath + "WEB-INF\\conf\\expert\\"
                    + ExpertExcelAction.XLS_EXPERT_LIST_TEMPLATE;
            List<ExpertBean> list = getBeanList();
            List<ExpertExcelBean> excelList = getExcelBeanList(list);

            Workbook wb = null;
            if (excelList.size() == 1) {
                wb = getService().exportExpert(templatePathSingle, excelList);
            } else {
                wb = getService().exportExpert(templatePathMulti, excelList);
            }
            baos = new ByteArrayOutputStream();
            wb.write(baos);
            baos.flush();
            byte[] excelBytes = baos.toByteArray();
            excelStream = new ByteArrayInputStream(excelBytes, 0, excelBytes.length);

            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            downloadFileName = "专家信息详细_" + sf.format(new Date()) + ".xls";
            downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！", e);
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
            }
        }
        return SUCCESS;
    }

    public String saveAutoSelectExpertCall() {
        map = new HashMap<String, Object>();
        try {
            if (expertIds == null || expertIds.isEmpty()) {
                throw new BaseException("错误：没有选择专家！");
            }
            String[] targetIds = expertIds.split(",");
            List<ExpertCallBean> callBeanList = new ArrayList<ExpertCallBean>();
            for (String id : targetIds) {
                Integer targetId = Integer.valueOf(id);
                ExpertCallBean call = new ExpertCallBean();
                ExpertBean expert = new ExpertBean();
                expert.setId(targetId);
                call.setTarget(expert);
                call.setCallName(expertCall.getCallName());
                call.setCallReason(expertCall.getCallReason());
                call.setCallRemark(expertCall.getCallRemark());
                call.setCallAim(expertCall.getCallAim());

                callBeanList.add(call);
            }

            callService.saveExpertCall(callBeanList);
            return SUCCESS;
        } catch (BaseException e) {
            map.put("errorMsg", e.getMessage());
            return ERROR;
        }
    }

    private List<ExpertExcelBean> getExcelBeanList(List<ExpertBean> expertList) {
        List<ExpertExcelBean> beanList = new ArrayList<ExpertExcelBean>();
        if (expertList == null || expertList.isEmpty()) {
            return beanList;
        }

        for (ExpertBean expert : expertList) {
            beanList.add(new ExpertExcelBean(expert));
        }
        return beanList;
    }
}

